from MySQLdb import connect, OperationalError

class Connection():
    def __init__(self, host, user, passwd, db):
        self.host = host
        self.user = user
        self.passwd = passwd
        self.db = db
        self.connect()

    def connect(self):
        self.db = connect(host=self.host, user=self.user, passwd=self.passwd, db=self.db)
        #db = connect(host='localhost', user='root', passwd='root', db='magento')
        self.db.set_character_set('utf8')
        self.cursor = self.db.cursor()
        self.cursor.execute('SET NAMES utf8;')
        self.cursor.execute('SET CHARACTER SET utf8;')
        self.cursor.execute('SET character_set_connection=utf8;')

    def sqlQuery(self, sql):
        try:
        #            print sql + "\n"
            self.cursor.execute(sql)
        except (AttributeError, OperationalError):
            if self.db:
                self.db.close()
            self.connect()
            self.cursor.execute(sql)
        finally:
            return self.cursor.fetchall()
